<?php
// +----------------------------------------------------------------------
// | 敏捷开发框架 [ 赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | 版权所有 2018~2023 优招网（上海）科技有限公司
// +----------------------------------------------------------------------
// | Licensed LGPL-3.0 并不是自由软件，未经许可禁止去掉相关版权
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | Author: @小码哥 团队荣誉出品
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------

declare (strict_types=1);

namespace app\admin\middleware;

/**
 * 跨域处理中间件
 * @author 小码哥
 * @since 2021/1/8
 * Class Cross
 * @package app\admin\middleware
 */
class Cross
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $response = $next($request);
        $origin = $request->header('Origin', '');

        // OPTIONS请求返回204请求
        if ($request->method(true) === 'OPTIONS') {
            $response->code(204);
        }
        $response->header([
            'Access-Control-Allow-Origin' => $origin,
            'Access-Control-Allow-Methods' => 'GET,POST,PUT',
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Allow-Headers' => '*',
        ]);

        return $response;
    }
}
